package com.example.yt_app.Activity.Device;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.ParseException;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.example.yt_app.Activity.BaseActivity.SwipeBackBaseActivity;
import com.example.yt_app.AppManager;
import com.example.yt_app.Fragment.CategoryThreeFragment;
import com.example.yt_app.R;
import com.example.yt_app.Urils.Delay;
import com.example.yt_app.Urils.Json;
import com.example.yt_app.Urils.SB_Parameter;
import com.example.yt_app.Urils.SPTool;
import com.example.yt_app.Urils.State;
import com.example.yt_app.Urils.Utils;
import com.example.yt_app.adapter.AnimationAdapter;
import com.example.yt_app.adapter.HistortyADapter;
import com.example.yt_app.animator.CustomAnimation1;
import com.example.yt_app.animator.CustomAnimation2;
import com.example.yt_app.bean.HistoricalData.Datapoints;
import com.example.yt_app.bean.HistoricalData.Datastreams;
import com.example.yt_app.bean.HistoricalData.HistoricalJsonRootBean;
import com.example.yt_app.bean.Status;
import com.gyf.immersionbar.BarHide;
import com.gyf.immersionbar.ImmersionBar;
import com.jaredrummler.materialspinner.MaterialSpinner;
import com.kyleduo.switchbutton.SwitchButton;
import com.lcodecore.tkrefreshlayout.footer.LoadingView;
import com.lcodecore.tkrefreshlayout.utils.LogUtil;
import com.manu.mdatepicker.FontType;
import com.manu.mdatepicker.MDatePicker;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import me.imid.swipebacklayout.lib.SwipeBackLayout;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by dell on 2021/8/2.
 */
@SuppressWarnings("ALL")
public class HistoryData extends SwipeBackBaseActivity {
    @Override
    protected SwipeBackLayout getSwipeBackLayout(int layoutId) {
        return null;
    }
    private OkHttpClient okHttpClient;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_historydata;
    }
    private HistortyADapter mHistortyADapter;
    @BindView(R.id.rv_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;

    @BindView(R.id.detail_toolbar)
    Toolbar toolbar;
    @BindView(R.id.spinner)
    MaterialSpinner spinner;
    @BindView(R.id.end_text)
    TextView End_text;
    @BindView(R.id.start_text)
    TextView Start_text;
    private String endtime;
    private String time;
    private String starttime;
    private mHandler mHandler = new mHandler();
    private final ArrayList<Map<String, Object>> list = new ArrayList<>();
    Map<String, Object> map;
    private  String id;
    @Override
    public void initView() {
        AppManager.getInstance().addActivity(this);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));




    }
    @Override
    protected void initData() {
        Date date = new Date(System.currentTimeMillis());
        endtime = Utils.Endtime(Utils.dateToString(date,"yyyy-MM-ddHH:mm:ss"));
        //自定义动画
        Intent i =getIntent();
        id= i.getStringExtra("id");

        initMenu() ;
        End_text.setText(Utils.dateToString(date,"yyyy-MM-dd HH:mm:ss"));
    }
    private void initMenu() {

        spinner.setItems("AlphaIn", "ScaleIn", "SlideInBottom", "SlideInLeft", "SlideInRight", "Custom1", "Custom2");
        spinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
            @Override
            public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
                switch (position) {
                    case 0:
                        mHistortyADapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.AlphaIn);
                        break;
                    case 1:
                        mHistortyADapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.ScaleIn);
                        break;
                    case 2:
                        mHistortyADapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.SlideInBottom);
                        break;
                    case 3:
                        mHistortyADapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.SlideInLeft);
                        break;
                    case 4:
                        mHistortyADapter.setAnimationWithDefault(BaseQuickAdapter.AnimationType.SlideInRight);
                        break;
                    case 5:
                        mHistortyADapter.setAdapterAnimation(new CustomAnimation1());
                        break;
                    case 6:
                        mHistortyADapter.setAdapterAnimation(new CustomAnimation2());
                        break;
                    default:
                        break;
                }
                mRecyclerView.setAdapter(mHistortyADapter);
            }
        });

    }


    public void Getdata(){
        okHttpClient = new OkHttpClient();
        /**
         * 函数：sort
         * 时间排序方式，DESC：倒序，ASC：升序，默认为ASC
         * */
        Request request = new Request.Builder()
                .url("http://api.heclouds.com/devices/"+id+"/datapoints?"
                        +"end="+ endtime+"&"+
                        "start="+Utils.Starttime(time)+"&"+
                        "sort=" +"DESC"
                        )
                .header("api-key", State.ApiKey).build();
        Call call =okHttpClient.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                try {

                    String responseData = response.body().string();
                    Log.i("TAG" , "postAsync" + responseData);
                    HistoricalJsonRootBean historicalJsonRootBean = Json.gson.fromJson(responseData, HistoricalJsonRootBean.class);
                    SB_Parameter.HISTORYLIST = historicalJsonRootBean.getData().getCount();
                    if (SB_Parameter.HISTORYLIST>0){
                        List<Datastreams> data = (List<Datastreams>) historicalJsonRootBean.getData().getDatastreams();
                        List<Datapoints> datapoints = (List<Datapoints>) data.get(0).getDatapoints();
                        System.out.println(historicalJsonRootBean.getData().getCount());
                        //System.out.println(data.get(0).getDatapoints().get(0).getValue());

                        for (int i = 0; i < historicalJsonRootBean.getData().getCount(); i++){
                            map = new HashMap<>();
                            String update_t = Utils.dateToString(datapoints.get(i).getAt(),"yyyy-MM-dd HH:mm:ss");
                            map.put("Value",  datapoints.get(i).getValue());
                            map.put("Time",  update_t);
                            list.add(map);
                        }
                        Message message = Message.obtain();
                        message.what = 1;
                        mHandler.sendMessage(message);
                    }
                    SB_Parameter.Getdata = false;
                } catch (IOException e){
                    e.printStackTrace();
                }
            }
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
            }
        });
    }
    private void initAdapter() {
        mHistortyADapter = new HistortyADapter(list);
        mHistortyADapter.setAnimationEnable(true);
        //int mFirstPageItemCount = 3;
        //mAnimationAdapter.setNotDoAnimationCount(mFirstPageItemCount);
        mHistortyADapter.addChildClickViewIds(R.id.tweetName, R.id.tweetText);

        mHistortyADapter.setAdapterAnimation(new CustomAnimation2());

        mHistortyADapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                String content = null;
                Status status = (Status) adapter.getItem(position);
                switch (view.getId()) {
//                    case R.id.img:
//                        content = "img:" + status.getUserAvatar();
//                        break;
                    case R.id.tweetName:
                        content = "name:" + status.getUserName();
                        break;
                    case R.id.tweetText:
                        content = "tweetText:" + status.getUserName();
                        break;
                    default:
                        break;
                }
                showMessage(content);
            }
        });
        mRecyclerView.setAdapter(mHistortyADapter);
        mHistortyADapter.setAnimationFirstOnly(false);

    }
    @Override
    protected void setListener() {
        //toolbar返回按钮监听
        toolbar.setNavigationOnClickListener(v ->finish() );
        //上拉加载底部view设置
        LoadingView loadingView = new LoadingView(getApplicationContext());
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                    Getdata();
                    refreshlayout.finishRefresh(1500/*,false*/);//传入false表示刷新失败

            }
        });
    }
    public void btnClickDateCenter(View view) {

        MDatePicker.create(this)
                .setCanceledTouchOutside(true)
                .setSupportTime(true)
                .setTwelveHour(true)
                .setFontType(FontType.NORMAL)
                .setOnDateResultListener(new MDatePicker.OnDateResultListener() {
                    @Override
                    public void onDateResult(long date) {
                        Message message = Message.obtain();
                        java.util.Calendar calendar = Calendar.getInstance();
                        calendar.setTimeInMillis(date);
                        java.text.SimpleDateFormat dateFormat = (java.text.SimpleDateFormat) SimpleDateFormat.getDateInstance();
                        dateFormat.applyPattern("yyyy-MM-ddHH:mm");
                        time = dateFormat.format(new Date(date));
                        message.what = 0;
                        mHandler.sendMessage(message);
                    }
                })
                .build()
                .show();
    }
    @OnClick({R.id.end_text,R.id.start_text})
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.end_text:

                break;
            case R.id.start_text:
                SB_Parameter.Getdata = true;
                btnClickDateCenter(v);

                break;
            default:
                throw new IllegalStateException("Unexpected value: " + v.getId());
        }
    }
    @SuppressWarnings("AliDeprecation")
    @SuppressLint("HandlerLeak")
    private class mHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Start_text.setText(time);
                    Getdata();
                    while (SB_Parameter.Getdata){
                        showMessage("请稍等...");
                        Delay.Delay_ms(500);
                    }

                    break;
                case 1:
                    initAdapter();

                    break;

                default:break;
            }
        }
    }
    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this).titleBar(toolbar).init();
        //隐藏状态栏
        ImmersionBar.with(this).hideBar(BarHide.FLAG_HIDE_STATUS_BAR).init();
        ImmersionBar.with(this).titleBar(R.id.detail_toolbar).keyboardEnable(true).init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
